package com.zhuo.project.order.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.zhuo.common.enums.SendStatus;
import com.zhuo.common.utils.SecurityUtils;
import com.zhuo.framework.aspectj.lang.annotation.Log;
import com.zhuo.framework.aspectj.lang.enums.BusinessType;
import com.zhuo.project.order.domain.ZzDiagnoseReturn;
import com.zhuo.project.order.domain.ZzDiagnoseSend;
import com.zhuo.project.order.service.IZzDiagnoseReturnService;
import com.zhuo.framework.web.controller.BaseController;
import com.zhuo.framework.web.domain.AjaxResult;
import com.zhuo.common.utils.poi.ExcelUtil;
import com.zhuo.framework.web.page.TableDataInfo;
import com.zhuo.project.order.service.IZzDiagnoseSendService;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

/**
 * 处方单退药明细Controller
 *
 * @author zhuo
 * @date 2020-03-26
 */
@Api("退药单操作")
@RestController
@RequestMapping("/order/return")
public class ZzDiagnoseReturnController extends BaseController {
    @Autowired
    private IZzDiagnoseReturnService zzDiagnoseReturnService;

    @Autowired
    private IZzDiagnoseSendService zzDiagnoseSendService;

    /**
     * 查询处方单退药明细列表
     */
    @PreAuthorize("@ss.hasPermi('order:return:list')")
    @GetMapping("/list")
    public TableDataInfo list(ZzDiagnoseReturn zzDiagnoseReturn) {
        startPage();
        List<ZzDiagnoseReturn> list = zzDiagnoseReturnService.selectZzDiagnoseReturnList(zzDiagnoseReturn);
        return getDataTable(list);
    }

    @ApiOperation("获取处方商品可退明细列表")
    @ApiImplicitParam(name = "diagnoseId", value = "处方ID", required = true, dataType = "String", paramType = "path")
    @PreAuthorize("@ss.hasPermi('order:head:list')")
    @GetMapping("/{diagnoseId}/list")
    public AjaxResult returnList(@PathVariable("diagnoseId") String diagnoseId) {
        List<ZzDiagnoseSend> list = zzDiagnoseSendService.selectZzDiagnoseSendListByDiagnoseId(diagnoseId);
        return AjaxResult.success(list);
    }

    /**
     * 导出处方单退药明细列表
     */
    @PreAuthorize("@ss.hasPermi('order:return:export')")
    @Log(title = "处方单退药明细", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(ZzDiagnoseReturn zzDiagnoseReturn) {
        List<ZzDiagnoseReturn> list = zzDiagnoseReturnService.selectZzDiagnoseReturnList(zzDiagnoseReturn);
        ExcelUtil<ZzDiagnoseReturn> util = new ExcelUtil<ZzDiagnoseReturn>(ZzDiagnoseReturn.class);
        return util.exportExcel(list, "return");
    }

    /**
     * 获取处方单退药明细详细信息
     */
    @PreAuthorize("@ss.hasPermi('order:return:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(zzDiagnoseReturnService.selectZzDiagnoseReturnById(id));
    }

    /**
     * 新增处方单退药明细
     */
    @PreAuthorize("@ss.hasPermi('order:return:add')")
    @Log(title = "处方单退药明细", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ZzDiagnoseReturn zzDiagnoseReturn) {
        return toAjax(zzDiagnoseReturnService.insertZzDiagnoseReturn(zzDiagnoseReturn));
    }


    @ApiOperation("保存退药信息")
    @ApiImplicitParam(name = "zzDiagnoseReturnList", value = "保存退药信息", dataType = "ZzDiagnoseReturn")
    @PreAuthorize("@ss.hasPermi('order:head:list')")
    @Log(title = "处方单退药批量新增", businessType = BusinessType.INSERT)
    @PostMapping("/batch/add")
    public AjaxResult batchAdd(@RequestBody List<ZzDiagnoseReturn> zzDiagnoseReturnList) {
        Map<String, List<ZzDiagnoseReturn>> diagnoseReturnMap = new HashMap<>();
        Date now = new Date();
        for (ZzDiagnoseReturn zzDiagnoseReturn : zzDiagnoseReturnList) {
            if (StrUtil.isBlank(zzDiagnoseReturn.getDiagnoseId())
                    || StrUtil.isBlank(zzDiagnoseReturn.getSendId())
                    || StrUtil.isBlank(zzDiagnoseReturn.getMaterialId())
                    || StrUtil.isBlank(zzDiagnoseReturn.getMaterialName())
                    // || StrUtil.isBlank(zzDiagnoseReturn.getBarcode())
                    || (null != zzDiagnoseReturn.getReturnQty()  && zzDiagnoseReturn.getReturnQty() < 0)
                    || ObjectUtil.isEmpty(zzDiagnoseReturn.getSendItemNo())) {
                return AjaxResult.error(3023, "参数错误");
            }
            if (null == zzDiagnoseReturn.getReturnQty() || zzDiagnoseReturn.getReturnQty() <= 0) {
                continue;
            }
            zzDiagnoseReturn.setSendStatus(2);
            zzDiagnoseReturn.setCreateBy(SecurityUtils.getUsername());
            zzDiagnoseReturn.setCreateTime(now);
            ZzDiagnoseSend zzDiagnoseSend = zzDiagnoseSendService.selectZzDiagnoseSendByItemNo(zzDiagnoseReturn.getSendId(),zzDiagnoseReturn.getSendItemNo(),zzDiagnoseReturn.getMaterialId());
            zzDiagnoseReturn.setReturnUnit(zzDiagnoseSend.getBaseQtyUnit());
            zzDiagnoseReturn.setReturnUnitName(zzDiagnoseSend.getBaseQtyUnitName());
            zzDiagnoseReturn.setIsValid(1);
            if (diagnoseReturnMap.containsKey(zzDiagnoseReturn.getSendId())) {
                diagnoseReturnMap.get(zzDiagnoseReturn.getSendId()).add(zzDiagnoseReturn);
            } else {
                List<ZzDiagnoseReturn> returnList = new ArrayList<>();
                returnList.add(zzDiagnoseReturn);
                diagnoseReturnMap.put(zzDiagnoseReturn.getSendId(), returnList);
            }
        }
        if (diagnoseReturnMap.size() <= 0) {
            return  AjaxResult.error(3024, "退药数量必须大于0");
        }
        try {
            int insertRows = zzDiagnoseReturnService.batchInsertZzDiagnoseReturnList(diagnoseReturnMap);
            return  toAjax(insertRows);
        }catch (Exception ex){
              logger.error(ex.getMessage());
              return AjaxResult.error(3026,ex.getMessage());
        }
    }


    /**
     * 修改处方单退药明细
     */
    @PreAuthorize("@ss.hasPermi('order:return:edit')")
    @Log(title = "处方单退药明细", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ZzDiagnoseReturn zzDiagnoseReturn) {
        return toAjax(zzDiagnoseReturnService.updateZzDiagnoseReturn(zzDiagnoseReturn));
    }

    /**
     * 删除处方单退药明细
     */
    @PreAuthorize("@ss.hasPermi('order:return:remove')")
    @Log(title = "处方单退药明细", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(zzDiagnoseReturnService.deleteZzDiagnoseReturnByIds(ids));
    }
}
